/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Friend;
import edu.cmu.fithub.db.bean.Schedule;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.db.bean.Workout;
import edu.cmu.fithub.db.bean.WorkoutDisplay;
import edu.cmu.fithub.formbeans.LoginForm;

public class DeleteWorkoutAction extends Action {

	private FormBeanFactory<LoginForm> formFactory = FormBeanFactory
			.getInstance(LoginForm.class);

	public DeleteWorkoutAction() {
	}

	public String getName() {
		return "deleteWorkout.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {
			User user = (User) request.getSession().getAttribute("user");
			int scheduleId = Integer.parseInt(request
					.getParameter("scheduleId"));
			int workoutId = Integer.parseInt(request.getParameter("workoutId"));
			Session dbSession = DBHelper.getSessionFactory().openSession();

			// delete the schedule based on the passed id.
			// delete all entries from the workout table that match the
			// schedule's workoutId (if the current userId also matches)
			String sched_query = "delete from Schedule where id='" + scheduleId
					+ "' AND userId='" + user.getUserId() + "'";
			String workout_query = "delete from Workout where workoutId='"
					+ workoutId + "' AND userId='" + user.getUserId() + "'";

			dbSession.beginTransaction();
			Query query = dbSession.createQuery(sched_query);
			int rowcount = query.executeUpdate();
			dbSession.createQuery(workout_query);

			query = dbSession.createQuery(workout_query);
			rowcount = query.executeUpdate();
			dbSession.getTransaction().commit();

			return "displayWorkout.do";

		} catch (NumberFormatException e) {

			return "error.jsp";
		}
	}
}
